"use client";

import { useEffect } from "react";
import Script from "next/script";
import Link from "next/link";
import geoJSON from "./coralMap.json";

// 定义高德地图相关类型
declare global {
  interface Window {
    AMap: {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      Map: any;
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      GeoJSON: any;
      GeometryUtil: {
        ringArea: (lnglats: number[]) => number;
      };
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      Polygon: any;
    };
  }
}

interface GeoJSONFeature {
  type: string;
  geometry: {
    type: string;
    coordinates: number[][][];
  };
  properties: Record<string, unknown>;
}

export default function CoralMapPage() {
  useEffect(() => {
    const initMap = () => {
      // 如果AMap已经加载，直接初始化
      if (!window.AMap) {
        setTimeout(() => {
          initMap();
        }, 500);
        return
      }
      const map = new window.AMap.Map("container", {
        center: [111.357465, 16.347794],
        zoom: 9,
        mapStyle: "amap://styles/58f7c54a2ce2e5ea704c30ea9f53cbaa",
      });

      const polygon = new window.AMap.GeoJSON({
        geoJSON: geoJSON,
        getPolygon: function (geojson: GeoJSONFeature, lnglats: number[][]) {
          // 计算面积
          const area = window.AMap.GeometryUtil.ringArea(lnglats[0]);

          return new window.AMap.Polygon({
            resizeEnable: true,
            path: lnglats,
            fillOpacity: 1 - Math.sqrt(area / 8000000000), // 面积越大透明度越高
            strokeColor: "white",
            fillColor: "red",
          });
        },
      });
      map.add(polygon);

    };
    setTimeout(() => {
      initMap();
    }, 500);
  }, []);

  return (
    <>
      <Link
        rel="stylesheet"
        href="//a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css"
      />
      <Script src="https://webapi.amap.com/maps?v=2.0&key=26507bfb54ab8c3a980b43ad03273a9f&plugin=AMap.GeoJSON" />
      <Script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js" />
      <div
        id="container"
        className="w-full"
        style={{ height: "calc(100vh - 81px)" }}
      />
    </>
  );
}
